<?php
require ('../include/init.inc.php');
$method = $machine_id = $page_no='';
extract ( $_GET, EXTR_IF_EXISTS );

$search_val = trim($_GET['searchVal']);

/*如果是download方法，进行导出操作*/
if($method == "download"){
	$filename = '客户信息'.date('YmdHis');
	$header = array('省份','城市','客户名称','联系人','客户地址','机型','机器序列号','拜访时间');
	$index = array('province','city','customer_name','real_user','customer_adress','machine_type','machine_number','talk_time');
	
	$customersList = Customer::getCusListBySearch($search_val);
	Customer::createtable($customersList,$filename,$header,$index);
}

/*如果是import方法，进行导出操作*/
if($method == "import"){
    /** 
    *  数据导入 
    * @param string $file excel文件 
    * @param string $sheet 
     * @return string   返回解析数据 
     * @throws PHPExcel_Exception 
     * @throws PHPExcel_Reader_Exception 
    */  
    function importExecl($file='', $sheet=0){  
        $file = iconv("utf-8", "gb2312", $file);   //转码  
        if(empty($file) OR !file_exists($file)) {  
            die('file not exists!');  
        }  
        include('./Excel/PHPExcel.php');  //引入PHP EXCEL类  
        $objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象  
        if(!$objRead->canRead($file)){  
            $objRead = new PHPExcel_Reader_Excel5();  
            if(!$objRead->canRead($file)){  
                die('No Excel!');  
            }  
        }  
      
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');  
      
        $obj = $objRead->load($file);  //建立excel对象  
        $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表  
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号  
        $columnCnt = array_search($columnH, $cellName);  
        $rowCnt = $currSheet->getHighestRow();   //获取总行数  
      
        $data = array();  
        for($_row=2; $_row<=$rowCnt; $_row++){  //读取内容  
            for($_column=0; $_column<=$columnCnt; $_column++){  
                $cellId = $cellName[$_column].$_row;  
                $cellValue = $currSheet->getCell($cellId)->getValue();  
                 //$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值  
                if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串  
                    $cellValue = $cellValue->__toString();  
                }  
      
                $data[$_row][$cellName[$_column]] = $cellValue;  
            }  
        }
        foreach ($data as $key => $value) {
        	$res[] =  array('unque_number' => $value['A'],'province' => $value['B'],'city' => $value['C'],'customer_name' => $value['D'],'real_user' => $value['E']
        	,'customer_adress' => $value['F'] ,'machine_type' => $value['G'] , 'machine_number' => $value['H'],'talk_time' => $value['I']);
        }  
        foreach ($res as $key => $value) {
        	$flag = Customer::addCustomer($value);
        }
        if ($res) {
            echo "<script>alert('添加成功！');window.location.href='./customer.php';</script>";
            
        }else{
            echo "<script>alert('添加失败！');window.location.href='./customer.php';</script>";
            exit();
        }
    }  

    //获取文件的大小  
    $file_size=$_FILES['upfile']['size'];  
    if($file_size>2*1024*1024) {  
        echo "文件过大，不能上传大于2M的文件";  
        exit();  
    }  
  
    $file_type=$_FILES['upfile']['type'];  
    // print_r($file_type);  exit;
    if($file_type!="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {  
        echo "文件类型只能为xlsx格式";  
        exit();  
    } 

    //判断是否上传成功（是否使用post方式上传）  
    if(is_uploaded_file($_FILES['upfile']['tmp_name'])) {  
        //把文件转存到你希望的目录（不要使用copy函数）  
        $uploaded_file=$_FILES['upfile']['tmp_name'];  
  
        //我们给每个用户动态的创建一个文件夹  
        $user_path="./upload";  
        //判断该用户文件夹是否已经有这个文件夹  
        if(!file_exists($user_path)) {  
            mkdir($user_path);  
        }  
  
        //$move_to_file=$user_path."/".$_FILES['myfile']['name'];  
        $file_true_name=$_FILES['upfile']['name'];  
        // $move_to_file=$user_path."/".time().rand(1,1000).substr($file_true_name,strrpos($file_true_name,"."));  
        $move_to_file=$user_path."/uploadExcel.xlsx";
        //echo "$uploaded_file   $move_to_file";  
        if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {  
            // echo $_FILES['upfile']['name']."上传成功";  
        } else {  
            // echo "上传失败";  
        }  
    } else {  
        // echo "上传失败";  
    }

    importExecl($move_to_file);
}

//START 数据库查询及分页数据
$row_count =Customer::count($search_val);
// echo $row_count;
$page_size = PAGE_SIZE;
$page_no=$page_no<1?1:$page_no;

$total_page=$row_count%$page_size==0?$row_count/$page_size:ceil($row_count/$page_size);
$total_page=$total_page<1?1:$total_page;
$page_no=$page_no>($total_page)?($total_page):$page_no;

$start = ($page_no - 1) * $page_size;



$customers = Customer::getCustomers($search_val,$start,$page_size);

$page_html=Pagination::showPager("customer.php?search_val=$search_val",$page_no,PAGE_SIZE,$row_count);


Template::assign ( 'page_no', $page_no );
Template::assign ( 'page_size', PAGE_SIZE );
Template::assign ( 'row_count', $row_count );
Template::assign ( 'page_html', $page_html );
Template::assign ( '_GET', $_GET );

$confirm_html = OSAdmin::renderJsConfirm("icon-remove");
Template::assign ( 'osadmin_action_confirm' , $confirm_html);
Template::assign ( 'customers', $customers );
Template::display ( 'panel/customer.tpl' );


